package com.fjnu.dao.impl;

import com.fjnu.annotation.NPECatch;
import com.fjnu.dao.UserDao;
import com.fjnu.entity.User;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * UserDao 实现类
 * 使用内存存储模拟数据库操作，用于测试Spring AOP功能
 * 包含@NPECatch注解用于测试异常捕获
 */
@Repository
@NPECatch // 类级别注解，捕获整个类的异常
public class UserDaoImpl implements UserDao {

    // 使用内存Map模拟数据库存储
    private final ConcurrentMap<String, User> userMap = new ConcurrentHashMap<>();
    private final AtomicInteger idCounter = new AtomicInteger(1);

    @Override
    public User selectById(String userId) {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        // 模拟数据库查询耗时
        simulateDatabaseDelay(100);
        return userMap.get(userId);
    }

    @Override
    public User selectByUsername(String username) {
        if (username == null || username.trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        simulateDatabaseDelay(150);
        return userMap.values().stream()
                .filter(user -> username.equals(user.getUsername()))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<User> selectAll() {
        simulateDatabaseDelay(200);
        return new ArrayList<>(userMap.values());
    }

    @Override
    public boolean insert(User user) {
        if (user == null) {
            throw new IllegalArgumentException("用户对象不能为空");
        }
        if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
            user.setUserId("user_" + idCounter.getAndIncrement());
        }
        if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
            throw new IllegalArgumentException("用户名不能为空");
        }

        simulateDatabaseDelay(250);
        userMap.put(user.getUserId(), user);
        return true;
    }

    @Override
    public boolean updateById(User user) {
        if (user == null) {
            throw new IllegalArgumentException("用户对象不能为空");
        }
        if (user.getUserId() == null || user.getUserId().trim().isEmpty()) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        simulateDatabaseDelay(180);
        if (!userMap.containsKey(user.getUserId())) {
            return false;
        }
        userMap.put(user.getUserId(), user);
        return true;
    }

    @Override
    public boolean deleteById(String userId) {
        if (userId == null || userId.trim().isEmpty()) {
            throw new IllegalArgumentException("用户ID不能为空");
        }

        simulateDatabaseDelay(120);
        return userMap.remove(userId) != null;
    }

    @Override
    public boolean validateUser(String username, String password) {
        if (username == null || password == null) {
            throw new IllegalArgumentException("用户名和密码不能为空");
        }

        simulateDatabaseDelay(170);
        User user = selectByUsername(username);
        return user != null && password.equals(user.getPassword());
    }

    @Override
    public int countUsers() {
        simulateDatabaseDelay(80);
        return userMap.size();
    }

    @Override
    @NPECatch // 方法级别注解，测试方法级别的异常捕获
    public boolean batchInsert(List<User> users) {
        if (users == null || users.isEmpty()) {
            throw new IllegalArgumentException("用户列表不能为空");
        }

        simulateDatabaseDelay(users.size() * 50);
        for (User user : users) {
            insert(user);
        }
        return true;
    }

    @Override
    public User selectByEmail(String email) {
        if (email == null || email.trim().isEmpty()) {
            throw new IllegalArgumentException("邮箱不能为空");
        }

        simulateDatabaseDelay(160);
        return userMap.values().stream()
                .filter(user -> email.equals(user.getEmail()))
                .findFirst()
                .orElse(null);
    }

    /**
     * 模拟数据库操作延迟
     * @param milliseconds 延迟毫秒数
     */
    private void simulateDatabaseDelay(int milliseconds) {
        try {
            Thread.sleep(milliseconds);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * 清空所有用户数据（用于测试）
     */
    public void clearAll() {
        userMap.clear();
        idCounter.set(1);
    }

    /**
     * 初始化测试数据（用于测试）
     */
    public void initTestData() {
        clearAll();

        User user1 = new User();
        user1.setUserId("test001");
        user1.setUsername("admin");
        user1.setPassword("admin123");
        user1.setEmail("admin@example.com");
        userMap.put(user1.getUserId(), user1);

        User user2 = new User();
        user2.setUserId("test002");
        user2.setUsername("user1");
        user2.setPassword("user123");
        user2.setEmail("user1@example.com");
        userMap.put(user2.getUserId(), user2);
    }
}